// eslint-disable-next-line no-unused-vars
import { getLoginInfo, login } from '@/api/admin/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, addRoutes } from '@/router'
import defaultSettings from '@/settings'
/* import { noticeMessage, stop } from '@/utils/signalR'
import { Notification } from 'element-ui' */
const state = {
  token: getToken(),
  name: '',
  avatar: require('@/assets/images/avatar.png'),
  menus: [],
  permissions: []
}

const mutations = {
  setToken: (state, token) => {
    state.token = token
    setToken(token)
  },
  setName: (state, name) => {
    state.name = name
  },
  setAvatar: (state, avatar) => {
    if (avatar) {
      state.avatar = avatar
    } else {
      state.avatar = require('@/assets/images/avatar.png')
    }
  },
  setMenus: (state, menus) => {
    state.menus = menus
  },
  setPermissions: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  async login({ commit }, paras) {
    const res = await login(paras)
    if (res && res.code === 1) {
      const token = res.data.accessToken
      commit('setToken', token)
    }

    return res
  },

  async getLoginInfo({ commit }) {
    const res = await getLoginInfo()
    if (!res.code === 1) {
      return res
    }
    const user = res.data

    if (!user) {
      return res
    }
    const name = user.trueName ? user.trueName : user.userName
    commit('setName', name)
    commit('setAvatar', defaultSettings.host + user.headPic)
    commit('setMenus', res.data.menus)
    commit('setPermissions', res.data.permissions)
    addRoutes(res.data.menus)

    /*  Notification({
      type: 'success',
      title: '消息提示',
      message: '你有' + res.data.msgCount + '条未读消息',
      position: 'bottom-right',
      onClick() {
        // 这里可以弹出展示消息列表
        // 弹出列表时候发送请求获取
        console.log('点击了消息框')
      }

    })
    noticeMessage('ReceiveMessage')*/
    return res
  },

  setLocalLoginInfo({ commit, dispatch, state }) {
    let loginInfo = window.localStorage.getItem('loginInfo')
    if (loginInfo) {
      loginInfo = JSON.parse(loginInfo)
      const user = loginInfo
      const name = user.trueName ? user.trueName : user.userName
      commit('setName', name)
      commit('setAvatar', user.headPic)
      commit('setMenus', loginInfo.menus)
      addRoutes(loginInfo.menus)
    } else {
      dispatch('logout')
    }
  },

  logout({ commit }) {
    commit('setToken', '')
    removeToken()
    resetRouter()
    sessionStorage.removeItem('tabs')
    commit('tabsView/delete_all_cached_views', null, { root: true })
    stop()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
